<template>
  <div class="echarts" id="echarts" ref="echarts"></div>
</template>
 
<script>
import store from "../store.js";
import * as echarts from "echarts";
export default {
  props: {
    isUpdate: Number,
    option: {
      type: Object,
      default: function () {
        return {
          type: "default",
        };
      },
    },
  },

  computed: {
    count() {
      return store.state.collapse;
    },
  },
  watch: {
    // 防止配置改变后不更新配置，重新加载配置即可
    option: {
      deep: true,
      handler() {
        if (this.chart) {
          this.chart.setOption(this.option);
        }
      },
    },
    // 自适应大小
    isUpdate(newVal, oldVal) {
      console.log(newVal);
      if (this.chart) {
        this.chart.resize();
      }
    },
    screenWidth(val) {
      let that = this;
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        console.log(val, "22222222222222");
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val;
        this.timer = true;
        setTimeout(function () {
          that.chart.resize();
          that.timer = false;
        }, 500);
      }
    },
    count(newVal, oldVal) {
      console.log(newVal);
      setTimeout(() => {
        this.chart.resize();
      }, 300);
    },
  },
  data() {
    return {
      chart: null,
      screenWidth: document.body.clientWidth,
    };
  },
  created() {
    console.log(store.state.collapse);
    const that = this;
    this.$nextTick(() => {
      this.initChart();
    });
    window.onresize = () =>
      (() => {
        console.log("111111111111111111111111111111");
        window.screenWidth = document.body.clientWidth;
        that.screenWidth = window.screenWidth;
      })();
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.echarts);
      if (this.option.type != "default") {
        this.chart.setOption(this.option);
      }
    },
  },
};
</script>
 
<style scoped="scoped">
.echarts {
  width: 100%;
  height: 100%;
}
</style>